package com.xhwl.centiotdata.handler.pedestrian.impl;

import com.alibaba.fastjson.JSON;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationFactory;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationHandler;
import com.xhwl.centiotdata.pojo.constant.MiLiConstant;
import com.xhwl.centiotdata.pojo.dto.mili.*;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.*;
import com.xhwl.centiotdata.service.impl.DeviceServiceImpl;
import com.xhwl.centiotdata.suppliersystem.mili.PedestrianMiLiHandler;
import com.xhwl.centiotdata.utils.Base64Utils;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.centiotdata.utils.UploadUtils;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.pedes.OpenDoorRecordDTO;
import com.xhwl.common.enums.*;
import com.xhwl.common.enums.pedestrian.DoorActionEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.query.cent.device.DeviceQuery;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/10/18 14:00
 */
@Service
@Slf4j
public class PedestrianIntegrationMiLiHandler extends PedestrianIntegrationHandler {

    @Autowired
    private PedestrianMiLiHandler pedestrianMiLiHandler;

    @Autowired
    private IPedestrianCentService pedestrianCentService;

    @Autowired
    private DeviceServiceImpl deviceService;

    @Autowired
    private IDeviceCentService iDeviceCentService;

    @Autowired
    private IAuthAccountCentService iAuthAccountCentService;

    @Autowired
    UploadUtils uploadUtilsService;

    @Autowired
    private IResidentInfoService iResidentInfoService;

    @Autowired
    private IAccountCentService iAccountCentService;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 米立人行
        PedestrianIntegrationFactory.register(ProductEnum.MILI_PEDESTRIAN.getId(), this);
    }

    /**
     * {
     * "accountIds": [
     * 36074
     * ],
     * "addedDeviceIdList": [
     * 701599
     * ],
     * "cardStatus": 0,
     * "categoryId": 1,
     * "deletedDeviceIdList": [],
     * "deviceGroupIdList": [],
     * "deviceIdList": [
     * 701599
     * ],
     * "industryId": 1,
     * "infoId": 1925,
     * "needTransition": false,
     * "objectId": 941,
     * "operatorId": 32582,
     * "operatorName": "test",
     * "projectId": 2385,
     * "sourceId": 36074,
     * "sourceType": 1,
     * "synType": [
     * 1
     * ],
     * "type": 1,
     * "validEndTime": 1668614400000,
     * "validStartTime": 1668387823770,
     * "validTime": 0
     * }
     */

    @Override
    public void pullVisits(PedestrianIntegrationConfigDTO configDTO, Date date) {
        // 拉取数据
        List<PedestrianRecordMiLiDTO> recordMiLiDTOList = pedestrianMiLiHandler.pullRecord(configDTO, date);
        if (CollectionUtils.isEmpty(recordMiLiDTOList)) {
            return;
        }
        // 转换数据
        List<OpenDoorRecordDTO> openDoorRecordDTOList = this.handleRecord(configDTO, recordMiLiDTOList);
        // 存储业务中台
        pedestrianCentService.saveBatch(openDoorRecordDTOList);
    }

    @Override
    public ResultJson openDoor(PedestrianIntegrationConfigDTO configDTO, DeviceDTO deviceDTO, DoorActionEnum doorAction) {
        return pedestrianMiLiHandler.openDoor(configDTO, deviceDTO, doorAction);
    }

    @Override
    public ResultJson createAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO) {
        log.info("米立新增权限: {}", JSON.toJSONString(pedestrianAuthDTO));
        List<DeviceDTO> deviceDTOS = deviceService.findDevice(pedestrianAuthDTO.getIndustryId(), null,
                CategoryEnum.DOOR.getId(), pedestrianAuthDTO.getDeviceIdList());
        // 米立人行
        List<String> deviceOpenList = deviceDTOS.stream()
                .filter(t -> t.getProductId().equals(ProductEnum.MILI_PEDESTRIAN.getId()))
                .map(DeviceDTO::getThirdDeviceId)
                .collect(Collectors.toList());
        List<String> cardList = Optional.ofNullable(pedestrianAuthDTO.getCardNumberList()).orElse(new LinkedList<>());
        if (pedestrianAuthDTO.getCardNumber() != null) {
            cardList.add(pedestrianAuthDTO.getCardNumber());
        }
        // 获取第三方的人员id
        List<String> userOpenIds = this.getOpenIds(pedestrianAuthDTO);
        log.info("-------------------------------------开始米立授权操作-------------------------------------");
        /**
         * 授权就是添加人脸/卡
         * 1.清除人脸/卡
         * 2.添加人脸/卡
         */
        List<Organization> organizationList = iResidentInfoService.getOrgListByAccountId(String.valueOf(pedestrianAuthDTO.getSourceId()), configDTO.getProjectId());
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isEmpty(organizationList)) {
            // 工作人员授权
            // 获取工作人员信息
            map.put("GuardID", userOpenIds.get(0));
            List<WorkerMiLiDTO> workerList = pedestrianMiLiHandler.queryWorker(configDTO, map);
            if (CollectionUtils.isEmpty(workerList)) {
                throw new BusinessException("米立工作人员不存在！");
            }
            // 新增人脸
            this.addFace(userOpenIds.get(0), workerList.get(0).getFaces(), pedestrianAuthDTO.getFaceUrl(), configDTO, 2);
            // 新增卡
            this.addCardList(userOpenIds.get(0), workerList.get(0).getCards(), cardList, configDTO, 2);
            try {
                log.info("米立保存转换卡数据");
                onSavingAuthCards(iAuthAccountCentService, configDTO, pedestrianAuthDTO);
            } catch (Exception e) {
                // 保存转换卡号数据失败
                log.error("米立保存卡数据异常", e);
            }
            if (StringUtils.isNotEmpty(pedestrianAuthDTO.getFaceUrl()) || !CollectionUtils.isEmpty(cardList)) {
                // 启用工作人员和选定设备的通行权限
                map.clear();
                map.put("ID", userOpenIds.get(0));
                map.put("DeviceNo", deviceOpenList);
                map.put("IsEnable", 1);
                pedestrianMiLiHandler.permissionWorker(configDTO, map);
                // 工作人员通行时效，暂未实现

            }
        } else {
            // 住户授权
            // 获取住户信息
            log.info("======米立第三方id： {}", userOpenIds);
            List<String> userInfo = Arrays.asList(userOpenIds.get(0).split(","));
            List<String> openIds = new ArrayList<>();
            for(String s : userInfo) {
                List<String> list = Arrays.asList(s.split("_"));
                String frameNo = list.get(0);
                String teneId = list.get(1);
                openIds.add(teneId);
                map.put("TeneID", teneId);
                map.put("PageIndex", 1);
                map.put("CountPrePage", 1);
                List<TenementMiLiDTO> tenementList = pedestrianMiLiHandler.queryTenement(configDTO, map);
                if (CollectionUtils.isEmpty(tenementList)) {
                    throw new BusinessException("米立住户不存在！");
                }
                // 新增人脸
                this.addFace(teneId, tenementList.get(0).getFaces(), pedestrianAuthDTO.getFaceUrl(), configDTO, 1);
                // 新增卡
                this.addCardList(teneId, tenementList.get(0).getCards(), cardList, configDTO, 1);
                try {
                    log.info("米立保存转换卡数据");
                    onSavingAuthCards(iAuthAccountCentService, configDTO, pedestrianAuthDTO);
                } catch (Exception e) {
                    // 保存转换卡号数据失败
                    log.error("米立保存卡数据异常", e);
                }
                // 设置住户通行时效
                Map<String, Object> mapTime = new HashMap<>();
                // 如果报错，改成mapTime.put("FrameNo", frameNo);
                mapTime.put("TeneNo", teneId);
                // mapTime.put("FrameNo", frameNo);
                mapTime.put("LimitDateTime", pedestrianAuthDTO.getValidEndTime());
                pedestrianMiLiHandler.setEffectiveDataTenement(configDTO, mapTime);
            }
            if (StringUtils.isNotEmpty(pedestrianAuthDTO.getFaceUrl()) || !CollectionUtils.isEmpty(cardList)) {
                // 启用住户和选定设备的通行权限
                Map<String, Object> mapPermission = new HashMap<>();
                mapPermission.put("ID", openIds);
                mapPermission.put("DeviceNo", deviceOpenList);
                mapPermission.put("IsEnable", 1);
                pedestrianMiLiHandler.permissionTenement(configDTO, mapPermission);
            }
        }
        return ResultJson.success();
    }

    @Override
    public ResultJson updateAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO) {
        log.info("米立更新权限: {}", JSON.toJSONString(pedestrianAuthDTO));
        List<String> cardList = Optional.ofNullable(pedestrianAuthDTO.getCardNumberList()).orElse(new LinkedList<>());
        if (pedestrianAuthDTO.getCardNumber() != null) {
            cardList.add(pedestrianAuthDTO.getCardNumber());
        }
        // 获取第三方的人员id
        List<String> userOpenIds = this.getOpenIds(pedestrianAuthDTO);
        List<Organization> organizationList = iResidentInfoService.getOrgListByAccountId(String.valueOf(pedestrianAuthDTO.getSourceId()), configDTO.getProjectId());
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isEmpty(organizationList)) {
            // 工作人员更新授权
            // 获取工作人员信息
            map.put("GuardID", userOpenIds.get(0));
            map.put("PageIndex", 1);
            map.put("CountPrePage", 1);
            List<WorkerMiLiDTO> workerList = pedestrianMiLiHandler.queryWorker(configDTO, map);
            // 新增卡
            this.addCardList(userOpenIds.get(0), workerList.get(0).getCards(), cardList, configDTO, 2);
            try {
                log.info("米立保存转换卡数据");
                onSavingAuthCards(iAuthAccountCentService, configDTO, pedestrianAuthDTO);
            } catch (Exception e) {
                // 保存转换卡号数据失败
                log.error("米立保存卡数据异常", e);
            }
            Set<String> deviceIdList = new HashSet<>();
            if (!CollectionUtils.isEmpty(pedestrianAuthDTO.getAddedThirdDeviceIdList())) {
                deviceIdList.addAll(pedestrianAuthDTO.getAddedThirdDeviceIdList());
            }
            if (!CollectionUtils.isEmpty(pedestrianAuthDTO.getThirdDeviceIdList())) {
                deviceIdList.addAll(pedestrianAuthDTO.getThirdDeviceIdList());
            }
            List<Right> rightList = workerList.get(0).getRights();
            map.clear();
            map.put("ID", userOpenIds);
            if (!CollectionUtils.isEmpty(rightList)) {
                List<String> deviceNOList = rightList.stream().map(Right::getDeviceNo).collect(Collectors.toList());
                /// {"ID":["3","4"],"DeviceNo":["000000003","010100000"],"IsEnable":"0"}
                // 门禁通行权限停用
                map.put("DeviceNo", deviceNOList);
                map.put("IsEnable", 0);
                pedestrianMiLiHandler.permissionWorker(configDTO, map);
            }
            if (!CollectionUtils.isEmpty(deviceIdList)) {
                // 门禁通行权限启用
                map.put("DeviceNo", deviceIdList);
                map.put("IsEnable", 1);
                pedestrianMiLiHandler.permissionWorker(configDTO, map);

            }
        } else {
            // 住户更新授权
            // 获取用户信息
            log.info("======米立第三方id： {}", userOpenIds);
            List<String> userInfo = Arrays.asList(userOpenIds.get(0).split(","));
            List<String> openIds = new ArrayList<>();
            for(String s : userInfo) {
                List<String> list = Arrays.asList(s.split("_"));
                String frameNo = list.get(0);
                String teneId = list.get(1);
                openIds.add(teneId);
                map.put("TeneID", teneId);
                map.put("PageIndex", 1);
                map.put("CountPrePage", 1);
                List<TenementMiLiDTO> tenementList = pedestrianMiLiHandler.queryTenement(configDTO, map);
                // 新增卡
                this.addCardList(teneId, tenementList.get(0).getCards(), cardList, configDTO, 1);
                try {
                    log.info("米立保存转换卡数据");
                    onSavingAuthCards(iAuthAccountCentService, configDTO, pedestrianAuthDTO);
                } catch (Exception e) {
                    // 保存转换卡号数据失败
                    log.error("米立保存卡数据异常", e);
                }
                Set<String> deviceIdList = new HashSet<>();
                if (!CollectionUtils.isEmpty(pedestrianAuthDTO.getAddedThirdDeviceIdList())) {
                    deviceIdList.addAll(pedestrianAuthDTO.getAddedThirdDeviceIdList());
                }
                if (!CollectionUtils.isEmpty(pedestrianAuthDTO.getThirdDeviceIdList())) {
                    deviceIdList.addAll(pedestrianAuthDTO.getThirdDeviceIdList());
                }
                List<Right> rightList = tenementList.get(0).getRights();
                map.clear();
                map.put("ID", Arrays.asList(teneId));
                if (!CollectionUtils.isEmpty(rightList)) {
                    List<String> deviceNOList = rightList.stream().map(Right::getDeviceNo).collect(Collectors.toList());
                    /// {"ID":["3","4"],"DeviceNo":["000000003","010100000"],"IsEnable":"0"}
                    // 门禁通行权限停用
                    map.put("DeviceNo", deviceNOList);
                    map.put("IsEnable", 0);
                    pedestrianMiLiHandler.permissionTenement(configDTO, map);
                }
                if (!CollectionUtils.isEmpty(deviceIdList)) {
                    // 门禁通行权限启用
                    map.put("DeviceNo", deviceIdList);
                    map.put("IsEnable", 1);
                    pedestrianMiLiHandler.permissionTenement(configDTO, map);
                    // 设置住户通行时效
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String limitDateTime = sdf.format(pedestrianAuthDTO.getValidEndTime());
                    map.clear();
                    // 这个参数文档里面是没有的，但是接口可以，如果报错，改成map.put("FrameNo", frameNo);
                    map.put("TeneNo", teneId);
                    //map.put("FrameNo", frameNo);
                    map.put("LimitDateTime", limitDateTime);
                    pedestrianMiLiHandler.setEffectiveDataTenement(configDTO, map);
                }
            }
        }
        return ResultJson.success();
    }

    @Override
    public ResultJson deleteAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO) {
        log.info("米立删除权限: {}", JSON.toJSONString(pedestrianAuthDTO));
        // 获取第三方的人员id
        List<String> userOpenIds = this.getOpenIds(pedestrianAuthDTO);
        List<Organization> organizationList = iResidentInfoService.getOrgListByAccountId(String.valueOf(pedestrianAuthDTO.getSourceId()), configDTO.getProjectId());
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isEmpty(organizationList)) {
            // 工作人员删除授权
            // 工作人员信息
            map.put("GuardID", userOpenIds.get(0));
            map.put("PageIndex", 1);
            map.put("CountPrePage", 1);
            List<WorkerMiLiDTO> workerList = pedestrianMiLiHandler.queryWorker(configDTO, map);
            // 删除权限
            List<Right> rightList = workerList.get(0).getRights();
            map.clear();
            map.put("ID", userOpenIds);
            if (!CollectionUtils.isEmpty(rightList)) {
                List<String> deviceNOList = rightList.stream().map(Right::getDeviceNo).collect(Collectors.toList());
                /// {"ID":["3","4"],"DeviceNo":["000000003","010100000"],"IsEnable":"0"}
                // 门禁通行权限停用
                map.put("DeviceNo", deviceNOList);
                map.put("IsEnable", 0);
                pedestrianMiLiHandler.permissionWorker(configDTO, map);
            }
        } else {
            // 住户删除授权
            // 住户信息
            log.info("======米立第三方id： {}", userOpenIds);
            List<String> userInfo = Arrays.asList(userOpenIds.get(0).split(","));
            List<String> openIds = new ArrayList<>();
            for(String s : userInfo) {
                List<String> list = Arrays.asList(s.split("_"));
                String teneId = list.get(1);
                openIds.add(teneId);
                map.put("TeneID", teneId);
                map.put("PageIndex", 1);
                map.put("CountPrePage", 1);
                List<TenementMiLiDTO> tenementList = pedestrianMiLiHandler.queryTenement(configDTO, map);
                // 删除权限
                List<Right> rightList = tenementList.get(0).getRights();
                map.clear();
                map.put("ID", Arrays.asList(teneId));
                if (!CollectionUtils.isEmpty(rightList)) {
                    List<String> deviceNOList = rightList.stream().map(Right::getDeviceNo).collect(Collectors.toList());
                    /// {"ID":["3","4"],"DeviceNo":["000000003","010100000"],"IsEnable":"0"}
                    // 门禁通行权限停用
                    map.put("DeviceNo", deviceNOList);
                    map.put("IsEnable", 0);
                    pedestrianMiLiHandler.permissionTenement(configDTO, map);
                }
            }
        }
        return ResultJson.success();
    }



    /**
     * 业主二维码
     *
     * @param configDTO
     * @return
     */
    @Override
    public ResultJson getInsideQrCode(PedestrianIntegrationConfigDTO configDTO, OpenDoorRecordDTO openDoorRecordDTO) {
        List<AuthAccountMapping> authAccountMappingList = iAuthAccountCentService.listByOpenIds(Arrays.asList(openDoorRecordDTO.getOpenUserId()));
        if(ChkUtil.isNull(authAccountMappingList)) {
            log.info("该人员未同步： {}  =====  {}", openDoorRecordDTO, authAccountMappingList);
            return ResultJson.fail("该人员未同步");
        }
        Account account = iAccountCentService.findById(authAccountMappingList.get(0).getAccountId());
        if(account == null) {
            log.error("该人员不存在: {}", openDoorRecordDTO);
            throw new BusinessException();
        }
        Object qrCode = redisUtils.get(String.format(MiLiConstant.TENEMENT_QRCODE_KEY, account.getId()));
        if(qrCode != null) {
            return ResultJson.success(qrCode);
        }
        return pedestrianMiLiHandler.getQrCode(configDTO, account);
    }



    private List<OpenDoorRecordDTO> handleRecord(PedestrianIntegrationConfigDTO configDTO, List<PedestrianRecordMiLiDTO> recordMiLiDTOList) {
        List<OpenDoorRecordDTO> openDoorRecordDTOList = new ArrayList<>();
        // 查询设备
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setThirdDeviceIdList(recordMiLiDTOList.stream().map(PedestrianRecordMiLiDTO::getDeviceNo).collect(Collectors.toList()));
        List<DeviceDTO> deviceDTOList = iDeviceCentService.listDevice(null, deviceQuery);
        Map<String, String> deviceMap = new HashMap<>();
        if(ChkUtil.isNotNull(deviceDTOList)) {
            deviceMap = deviceDTOList.stream().collect(Collectors.toMap(DeviceDTO::getThirdDeviceId, DeviceDTO::getName));
        }

        for(PedestrianRecordMiLiDTO recordMiLiDTO : recordMiLiDTOList) {
            OpenDoorRecordDTO openDoorRecordDTO = new OpenDoorRecordDTO();
            openDoorRecordDTO.setProjectId(configDTO.getProjectId());
            openDoorRecordDTO.setProductId(ProductEnum.MILI_PEDESTRIAN.getId());
            openDoorRecordDTO.setOpenUserId(recordMiLiDTO.getPersonIdentify());
            openDoorRecordDTO.setArrivalTime(recordMiLiDTO.getEventTime());
            if(ChkUtil.isNotNull(recordMiLiDTO.getImageFile())) {
                openDoorRecordDTO.setPictureUrl(uploadUtilsService.uploadImgBase64(recordMiLiDTO.getImageFile()));
            }
            openDoorRecordDTO.setState((short) 1);
            // 查询住户信息
            Map<String, Object> map = new HashMap<>();
            map.put("TeneID", recordMiLiDTO.getPersonIdentify());
            map.put("PageIndex", 1);
            map.put("CountPrePage", 1);
            List<TenementMiLiDTO> tenementList = pedestrianMiLiHandler.queryTenement(configDTO, map);
            if(ChkUtil.isNotNull(tenementList)) {
                openDoorRecordDTO.setUserName(tenementList.get(0).getName());
            }
            openDoorRecordDTO.setOpenDeviceId(recordMiLiDTO.getDeviceNo());
            openDoorRecordDTO.setDeviceName(deviceMap.get(recordMiLiDTO.getDeviceNo()));
            if(ChkUtil.isNotNull(recordMiLiDTO.getEventDesc())) {
                if(recordMiLiDTO.getEventDesc().contains("出门")) {
                    openDoorRecordDTO.setDirection(DirectionEnum.OUT.getId());
                } else if(recordMiLiDTO.getEventDesc().contains("进门")) {
                    openDoorRecordDTO.setDirection(DirectionEnum.IN.getId());
                } else {
                    openDoorRecordDTO.setDirection(DirectionEnum.UNKNOWN.getId());
                }
            }
            openDoorRecordDTO.setSourceType(SourceTypeEnum.USER.type);
            openDoorRecordDTO.setType(handleAccessType(recordMiLiDTO.getEventType()));
            openDoorRecordDTO.setCode(String.valueOf(recordMiLiDTO.getFlowNo()));

            openDoorRecordDTOList.add(openDoorRecordDTO);
        }
        return openDoorRecordDTOList;
    }

    private Short handleAccessType(int eventType) {
        switch (eventType) {
            case 1:
                return AccessTypeEnum.IC_CARD.getId();
            case 2:
                return AccessTypeEnum.PASS_WORD.getId();
            case 3:
                return AccessTypeEnum.QR_CODE.getId();
            case 4:
                return AccessTypeEnum.FACE.getId();
            case 5:
                return AccessTypeEnum.FINGERPRINT.getId();
            case 6:
                return AccessTypeEnum.BUTTON.getId();
            case 13:
                return AccessTypeEnum.REMOTE.getId();
            default:
                return AccessTypeEnum.OTHER.getId();
        }
    }

    private List<String> getOpenIds(PedestrianAuthDTO pedestrianAuthDTO) {
        List<String> userOpenIds = pedestrianAuthDTO.getUserOpenIds();
        if (CollectionUtils.isEmpty(userOpenIds)) {
            String userOpenId = pedestrianAuthDTO.getUserOpenId();
            if (StringUtils.isNotEmpty(userOpenId)) {
                userOpenIds = Collections.singletonList(userOpenId);
            } else {
                Integer accountId = pedestrianAuthDTO.getAccountId();
                if (Objects.nonNull(accountId)) {
                    AuthAccountMapping authA = iAuthAccountCentService.query(pedestrianAuthDTO.getProjectId(), accountId, pedestrianAuthDTO.getProductId());
                    if (Objects.nonNull(authA) && StringUtils.isNotEmpty(authA.getOpenId())) {
                        userOpenIds = Collections.singletonList(authA.getOpenId());
                    }
                } else {
                    List<Integer> accountIds = pedestrianAuthDTO.getAccountIds();
                    if (Objects.nonNull(accountIds)) {
                        Set<String> openIds = new HashSet<>();
                        accountIds.forEach(t -> {
                            AuthAccountMapping authA = iAuthAccountCentService.query(pedestrianAuthDTO.getProjectId(), t, pedestrianAuthDTO.getProductId());
                            if (Objects.nonNull(authA) && StringUtils.isNotEmpty(authA.getOpenId())) {
                                openIds.add(authA.getOpenId());
                            }
                        });
                        userOpenIds = new ArrayList<>(openIds);
                    }
                }
            }
        }
        return userOpenIds;
    }

    /**
     * @param userId
     * @param delCardList
     * @param addCardList
     * @param configDTO
     * @param personType  1：住户，2：工作人员
     */
    private void addCardList(String userId, List<String> delCardList, List<String> addCardList, PedestrianIntegrationConfigDTO configDTO, int personType) {
        Map<String, Object> map = new HashMap<>();
        map.put("TeneID", userId);
        map.put("PersonType", personType);
        if (!CollectionUtils.isEmpty(delCardList)) {
            delCardList.forEach(e -> {
                map.put("CardNo", e);
                pedestrianMiLiHandler.delCard(configDTO, map);
            });
        }
        if (!CollectionUtils.isEmpty(addCardList)) {
            // 添加
            addCardList.forEach(e -> {
                map.put("CardNo", e);
                pedestrianMiLiHandler.addCard(configDTO, map);
            });
        }
    }

    /**
     * @param userId
     * @param delFaceList
     * @param addFaceUrl
     * @param configDTO
     * @param personType  1：住户，2：工作人员
     */
    public void addFace(String userId, List<Face> delFaceList, String addFaceUrl, PedestrianIntegrationConfigDTO configDTO, int personType) {
        Map<String, Object> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(delFaceList)) {
            // 删除住户人脸
            delFaceList.forEach(e -> {
                map.clear();
                map.put("FaceID", e.getID());
                pedestrianMiLiHandler.removeFaceById(configDTO, map);
            });
        }
        // 如果人脸不为空，新增米立人脸
        if (StringUtils.isNotEmpty(addFaceUrl)) {
            map.clear();
            map.put("ID", userId);
            map.put("PersonType", personType);
            map.put("Photo", "data:image/jpeg;base64," + Base64Utils.imageUrlToBase64(addFaceUrl));
            pedestrianMiLiHandler.addFace(configDTO, map);
        }
    }
}
